package com.shh.shojbackendquestionservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shh.shojbackendcommon.common.ErrorCode;
import com.shh.shojbackendcommon.constant.CommonConstant;
import com.shh.shojbackendcommon.exception.BusinessException;
import com.shh.shojbackendcommon.utils.SqlUtils;
import com.shh.shojbackendmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.shh.shojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.shh.shojbackendmodel.model.entity.Question;
import com.shh.shojbackendmodel.model.entity.QuestionSubmit;
import com.shh.shojbackendmodel.model.entity.User;
import com.shh.shojbackendmodel.model.enums.QuestionSubmitLanguageEnum;
import com.shh.shojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.shh.shojbackendmodel.model.vo.QuestionSubmitVO;
import com.shh.shojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.shh.shojbackendquestionservice.rabbmitmq.MyMessageProducer;
import com.shh.shojbackendquestionservice.service.QuestionService;
import com.shh.shojbackendquestionservice.service.QuestionSubmitService;
import com.shh.shojbackendserviceclient.service.JudgeFeignClient;
import com.shh.shojbackendserviceclient.service.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author yuppie
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2025-03-27 23:22:44
*/
@Service
@Slf4j
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;


    @Resource
    private UserFeignClient userService;

    @Resource
    //只有在第一次被请求时才会创建实例，而不是在应用启动时就初始化
    @Lazy
    private JudgeFeignClient judgeService;

    @Resource
    private MyMessageProducer myMessageProducer;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        String language = questionSubmitAddRequest.getLanguage();
        //通过枚举类获取枚举对象
        QuestionSubmitLanguageEnum languageValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言不存在");
        }

        long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        //从枚举类中获取枚举对象
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        Long QuestionSubmitId = questionSubmit.getId();
        //在消费者中初始化消息队列时 定义了exchange和routingKey 通过这两个参数才能找到相应的消息队列
        myMessageProducer.sendMessage("code_exchange","my_routingKey", String.valueOf(QuestionSubmitId));
        //执行判题服务 异步执行
//        CompletableFuture.runAsync(() -> {
//            System.out.println("开始执行判题服务");
//            //将要传输的信息先放入消息队列中
//             judgeService.doJudge(QuestionSubmitId);
//        });

        return questionSubmit.getId();
    }

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        //QueryWrapper<QuestionSubmit> 中的泛型 QuestionSubmit 是实体类，MyBatis-Plus 会根据这个实体类找到对应的表。
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 1. 关联查询用户信息
        Long userId = loginUser.getId();
        //如果当前用户不是题目提交者 并且不是管理员则不提供代码信息
        if(userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    /**
     * 这里就是使用了循环，降每一条查出来的信息进行封装后再返回
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage,  User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        //理解 先将要处理的数据转换为stream流 然后再用map对这些数据根据自己的规则进行筛选 筛选完再收集为原来的数据类型 将stream流中每个元素赋值为questionSubmit
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                // -> 左边是参数 右边是函数体
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    /**
     * 获取当前用户当前题目提交信息
     * @param userId
     * @param questionId
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQuestionSubmitUserVOList(Long userId, Long questionId) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        return queryWrapper;
    }
}




